
import type { RootState } from "../store/index";
import { logins } from "../store/modules/user_data"
import { login } from '../api/userInfo'
import { useDispatch, useSelector } from 'react-redux';
import { Navigate } from "react-router-dom";
import { Spin } from 'antd';
import { useEffect, useState } from "react";

// 添加权限
const PrivateRoute = (props: any) => {
  const [spinning, setSpinning] = useState(false);
  let token = useSelector((state: RootState) => state.userData.token);
  let userinfo: any = useSelector((state: RootState) => state.userData.userinfo);
  const dispatch = useDispatch();
  let isAuthenticated = token
  useEffect(() => {
    if (token && !userinfo.username) {
      setSpinning(true)
      login({ token: token }).then((res: any) => {
        dispatch(logins(res.userinfo));
      }).finally(() => {
        setSpinning(false)
      })
    }
  });
  return (
    <div>
      {
        isAuthenticated ? props.children : <Navigate to="/login" />
      }
      <Spin spinning={spinning} fullscreen />
    </div>
  )
};


export default PrivateRoute